// @ts-nocheck
import React, { FC, useState, useEffect, useMemo } from "react";
import {
  NavBar,
  Button,
  Form,
  Input,
  Cascader,
  TextArea,
  ImageUploader,
  Toast,
} from "antd-mobile";
import { Spin } from "antd";
import { useNavigate } from "react-router-dom";
import { CascaderOption } from "antd-mobile/es/components/cascader";
// service
import {
  getTypes,
  putEventReportByFromData,
  upLoadImage,
} from "./service";
import { getCurrentUser } from "@/utils/authority";
import { HandOk } from "@/components";

// style
import "./index.less";

interface IFormState {
  title: string;
  type: string[];
  address: string;
  addressDetailedUser: string;
  content: string;
}

interface IStartFormState {
  questiontitle: string;
  eventType: string;
  desc: string; //描述
  fileFront: [];
  // fileBack:string[];
}

function EventReport() {
  const userId = getCurrentUser()?.data?.user_id;
  const [loaing, setLoaing] = useState(false);
  const [handOk, setHandOk] = useState(false)
  const [users, setUser] = useState({})
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [visible, setVisible] = useState(false);
  const [ImageList, setImageList] = useState<{ url: string; name: string }[]>([]);
  const [eventList, setEventList] = useState<CascaderOption[]>([]);

  const onFinish = async (values: IFormState) => {
    const attachList: [] = ImageList.map((item) => {
      return item.url;
    });
    if (Array.isArray(attachList)) {
      console.log(attachList);

    }
    // setLoaing(true);
    const formCommitData: IStartFormState = {
      complaintId: users.user_id,
      complaintName: users.real_name,
      complaintPhone: users.account,
      villageCode: users?.villageCode || "511602006004",
      title: values.title,
      type: values.type[0],
      replyContent: values.replyContent,
      img: attachList,
    };
    try {
      const parma = formCommitData;
      const { success } = await putEventReportByFromData(parma);
      if (!success) {
        Toast.show({
          icon: "fail",
          content: "上报失败",
        });
        setLoaing(false);
        return;
      }
      if (success) {
        setLoaing(false);
        Toast.show({
          icon: "success",
          content: "上报成功",
        });
        setHandOk(true)

      }
    } catch (err) {
      console.error(err);
    }
  };

  const getEventTypeList = async () => {
    try {
      const { data, code, msg } = await getTypes({ code: "communnity_type" });
      if (code === 200) {
        const arr = data.map(item => {
          return {
            label: item?.dictValue,
            value: item?.dictValue
          }
        })
        setEventList(arr)
      }
    } catch (err) {
      console.error(err);
    }
  };

  async function mockUpload(file: File) {
    try {
      const { data } = await upLoadImage({ file: file });
      if (data?.code === 200) {
        Toast.show({
          icon: "success",
          content: "上传成功",
        });
        const url = data.data.length && data.data[0].link;
        const name = data.data.length && data.data[0].name;
        return {
          url,
          name,
        };
      } else {
        Toast.show({
          icon: "fail",
          content: data.msg,
        });
        return {
          url: "",
        };
      }
    } catch (err) {
      Toast.show({
        icon: "fail",
        content: "上传失败",
      });
      return {
        url: "",
      };
    }
  }

  useEffect(() => {
    const formItem = JSON.parse(
      localStorage.getItem("form") || JSON.stringify("")
    );
    form.setFieldsValue(formItem);

    const users = JSON.parse(
      localStorage.getItem("users") || JSON.stringify({})
    );
    setUser(users)
    getEventTypeList();
    return () => {
      localStorage.removeItem("form");
      form.resetFields();
    };
  }, []);

  const Basic = useMemo(() => {
    return (
      <div>
        <div className="figImg">多添加图片，能更清晰的表明事件地点</div>
        <ImageUploader
          maxCount={3}
          showUpload={ImageList.length < 3}
          value={ImageList}
          onChange={setImageList}
          upload={mockUpload}
          multiple={false}
          capture={true}
        />
      </div>
    );
  }, [ImageList]);
  const handleChange = () => {
    form
      .validateFields()
      .then((formValue) => { })
      .catch(() => {
        const vals = form.getFieldsValue();
      });
  };
  return (
    handOk ? <HandOk topTitle="感谢您的建议" title="请等待社区反馈" header='社区回音壁' />
      :
      <Spin tip="提交中..." spinning={loaing}>
        <div className="reportcontent">
          <div>
            <NavBar
              onBack={() => navigate(-1)}
            >
              <div className="commontitle">社区回音壁</div>
            </NavBar>
          </div>

          <div className="eventFrom">
            {users?.account ?
              <Form form={form} onFinish={onFinish}
                initialValues={{
                  villageCode: "广安区中桥街道解放社区"
                }}
              >
                <Form.Item
                  name="villageCode"
                  label="接收社区"
                  rules={[{ required: true, message: "必填项" }]}
                >
                  <Input placeholder="请输入接收社区" disabled />
                </Form.Item>
                <Form.Item
                  name="type"
                  label="类型"
                  trigger="onConfirm"
                  onClick={() => {
                    setVisible(true);
                  }}
                  rules={[{ required: true, message: "必填项" }]}
                >
                  <Cascader
                    options={eventList}
                    visible={visible}
                    onClose={() => {
                      setVisible(false);
                    }}
                  >
                    {(items) => {
                      if (items.every((item) => item === null)) {
                        return <div className="colour">点击选择类型</div>;
                      } else {
                        return items[items.length - 1]?.label;
                      }
                    }}
                  </Cascader>
                </Form.Item>
                <Form.Item
                  name="title"
                  label="标题"
                  rules={[{ required: true, message: "必填项" }]}
                >
                  <Input placeholder="请输入标题" />
                </Form.Item>
                <Form.Item
                  name="replyContent"
                  label="描述"
                  className="eventContent"
                  rules={[{ required: true, message: "必填项" }]}
                >
                  <TextArea placeholder="请输入描述" rows={4} />
                </Form.Item>

                <Form.Item
                  label="照片"
                  rules={[{ required: true, message: "必填项" }]}
                  className="BasicBox"
                >
                  {Basic}
                </Form.Item>
                <div className="bottomButton">
                  <Button
                    onClick={(e) => {
                      if (!loaing) {
                        e.preventDefault();
                        form.submit();
                      }
                    }}
                    type="submit"
                    className="reportbtn "
                    style={{ fontSize: "1.5rem" }}
                  >
                    {loaing ? "提交中" : "提交"}
                  </Button>
                </div>
              </Form> : null
            }


          </div>
        </div>
      </Spin>
  );
}

export default EventReport;
